#include "musicform3.h"
#include "ui_musicform3.h"
#include <QMouseEvent>
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include "customdelegete.h" // 引入自定义代理类

MusicForm3::MusicForm3(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MusicForm3),
    pModelForm3(new QStandardItemModel(0, 5, this)) // 初始化模型，行数设置为0，列数为5

{
    ui->setupUi(this);

    // 设置表头
    QStringList list1 = QStringList() << "歌名" << "专辑" << "歌手" << "时长" << "收藏状态";
    pModelForm3->setHorizontalHeaderLabels(list1);
    ui->tableViewF3->setModel(pModelForm3);

    // 使用自定义代理类
    customDelegete *delegate = new customDelegete();
    ui->tableViewF3->setItemDelegateForColumn(5, delegate); // 设置收藏状态列使用自定义代理

    // 设置定时器每5秒刷新一次
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MusicForm3::loadFavoriteSongs_3);
    timer->start(500); // 每5秒刷新

    // 初始加载数据
    loadFavoriteSongs_3();
    ui->tableViewF3->verticalHeader()->setVisible(false); // 隐藏垂直表头
}

// 加载收藏的歌曲
void MusicForm3::loadFavoriteSongs_3() {
    // 清空模型
      pModelForm3->clear();
      // 重新设置表头
      QStringList list1 = QStringList() << "ID" << "歌名" << "专辑" << "歌手" << "时长" << "收藏状态";
      pModelForm3->setHorizontalHeaderLabels(list1);

      // 初始化数据库查询
      QSqlQuery query;

      // SQL 查询，提取所有信息
      QString sql = "SELECT id, song_name, album, singer, duration, favorite FROM music";
      if (query.exec(sql)) {
          int row = 0;
          while (query.next()) {
              // 获取ID并存储在变量中
              int songID = query.value(0).toInt(); // 获取第一列的ID
              QString songName = query.value(1).toString();
              QString albumName = query.value(2).toString();
              QString singerName = query.value(3).toString();
              QString duration = query.value(4).toString();
              QString favoriteStatus = query.value(5).toString(); // 收藏状态

              // 将数据填充到模型中
              pModelForm3->setItem(row, 0, new QStandardItem(QString::number(songID))); // 显示ID
              pModelForm3->setItem(row, 1, new QStandardItem(songName));
              pModelForm3->setItem(row, 2, new QStandardItem(albumName));
              pModelForm3->setItem(row, 3, new QStandardItem(singerName));
              pModelForm3->setItem(row, 4, new QStandardItem(duration));
              pModelForm3->setItem(row, 5, new QStandardItem(favoriteStatus));

              row++;
          }
      } else {
          qDebug() << "数据库查询失败: " << query.lastError();
      }

}

// 处理鼠标点击事件
void MusicForm3::mouseDoubleClickEvent(QMouseEvent *event) {
    QModelIndex index = ui->tableViewF3->indexAt(event->pos()); // 获取鼠标点击位置的索引
    if (index.isValid() && index.column() == 4) { // 确保点击的是有效索引，并且是收藏状态的列
        QString songName = pModelForm3->item(index.row(), 0)->text(); // 获取歌曲名
        QString currentStatus = index.data().toString(); // 获取当前收藏状态

        if (currentStatus == "未收藏") { // 只有未收藏状态才会进行取消收藏的操作
            // 切换收藏状态
            QString newStatus = "已收藏";
            pModelForm3->item(index.row(), 4)->setText(newStatus); // 更新模型中的收藏状态

            // 更新数据库
            QSqlQuery query;
            QString updateSql = "UPDATE music SET favorite = ? WHERE song_name = ?"; // 更新语句
            query.prepare(updateSql);
            query.addBindValue(newStatus);
            query.addBindValue(songName); // 绑定参数
            if (!query.exec()) {
                QMessageBox::warning(this, "错误", "更新收藏状态失败: " + query.lastError().text()); // 更新失败时弹出警告框
            }
        }
    }
}


MusicForm3::~MusicForm3() {
    delete ui; // 释放内存
}

void MusicForm3::on_tableViewF3_clicked(const QModelIndex &index)
{
    if(index.column() != 5) // If not the 4th column (Favorite column), do nothing.
    {
        return;
    }

    QVariant ret = pModelForm3->data(index); // Get the current value from the model
    QStandardItem *item = pModelForm3->item(index.row(), index.column());
    QString songIId = pModelForm3->item(index.row(), 0)->text();
    QString songName = pModelForm3->item(index.row(), 1)->text(); // Assuming songName is in the first column
    QString singerName = pModelForm3->item(index.row(), 3)->text(); // Assuming singerName is in the third column
    QString albumName = pModelForm3->item(index.row(), 2)->text(); // Assuming albumName is in the second column
    QString duration = pModelForm3->item(index.row(), 4)->text(); // Assuming duration is in the fourth column

    // 初始化数据库查询
        QSqlQuery query;

        // SQL 查询，提取所有信息
        QString sql = "SELECT id FROM music"; // 只选择ID
        if (query.exec(sql)) {
            while (query.next()) {
                // 获取ID并存储在变量中
                int songID = query.value(0).toInt(); // 获取ID
                qDebug() << "Song ID: " << songID; // 输出ID以确认

                // 如果需要做其他操作，可以在这里使用 songID
            }
        } else {
            qDebug() << "数据库查询失败: " << query.lastError();
        }

    if (ret == "未收藏") {
        // Change to "已收藏"
        pModelForm3->setItem(index.row(), index.column(), new QStandardItem("已收藏"));

        // Insert song into the database
        QSqlQuery query;
        query.prepare("INSERT INTO music (id, song_name, singer, album, duration, favorite) "
                      "VALUES (:id, :song_name, :singer, :album, :duration, :favorite)");

        query.bindValue(":id", songIId);
        query.bindValue(":song_name", songName);
        query.bindValue(":singer", singerName);
        query.bindValue(":album", albumName);
        query.bindValue(":duration", duration);
        query.bindValue(":favorite", "已收藏");

        if (!query.exec()) {
            qDebug() << "Failed to insert data: " << query.lastError();
        }
    } else if (ret == "已收藏") {
        // Change to "未收藏"
        pModelForm3->setItem(index.row(), index.column(), new QStandardItem("未收藏"));

        // Delete song from the database
        QSqlQuery query;
        query.prepare("DELETE FROM music WHERE id = :id");
        query.bindValue(":id", songIId);

        if (!query.exec()) {
            qDebug() << "Failed to delete data: " << query.lastError();
        }
    }
}
